package com.businesscard.system.service.impl;

import com.businesscard.system.entity.BusinessCardFolder;
import com.businesscard.system.mapper.BusinessCardFolderMapper;
import com.businesscard.system.mapper.BusinessCardMapper;
import com.businesscard.system.service.BusinessCardFolderService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import java.util.List;

/**
 * 名片夹服务实现
 */
@Service
public class BusinessCardFolderServiceImpl implements BusinessCardFolderService {

    @Autowired
    private BusinessCardFolderMapper folderMapper;
    
    @Autowired
    private BusinessCardMapper cardMapper;

    @Override
    public boolean createFolder(BusinessCardFolder folder) {
        return folderMapper.insertFolder(folder) > 0;
    }

    @Override
    public boolean updateFolder(BusinessCardFolder folder) {
        return folderMapper.updateFolder(folder) > 0;
    }

    @Override
    public BusinessCardFolder getFolderById(Integer id) {
        return folderMapper.selectFolderById(id);
    }

    @Override
    public List<BusinessCardFolder> getFoldersByUserId(Integer userId) {
        List<BusinessCardFolder> folders = folderMapper.selectFoldersByUserId(userId);
        // 为每个名片夹填充名片数量
        if (folders != null) {
            for (BusinessCardFolder folder : folders) {
                Integer cardCount = cardMapper.countCardsByFolderId(folder.getId());
                folder.setCardCount(cardCount != null ? cardCount : 0);
            }
        }
        return folders;
    }

    @Override
    public List<BusinessCardFolder> getDeletedFoldersByUserId(Integer userId) {
        return folderMapper.selectDeletedFoldersByUserId(userId);
    }

    @Override
    @Transactional
    public boolean deleteFolder(Integer id) {
        // 逻辑删除名片夹下的所有名片
        cardMapper.logicalDeleteCardsByFolderId(id);
        // 逻辑删除名片夹
        return folderMapper.logicalDeleteFolder(id) > 0;
    }

    @Override
    @Transactional
    public boolean restoreFolder(Integer id) {
        // 恢复名片夹下的所有名片
        cardMapper.restoreCardsByFolderId(id);
        // 恢复名片夹
        return folderMapper.restoreFolder(id) > 0;
    }

    @Override
    @Transactional
    public boolean removeFolder(Integer id) {
        // 彻底删除名片夹下的所有名片
        cardMapper.deleteCardsByFolderId(id);
        // 彻底删除名片夹
        return folderMapper.deleteFolder(id) > 0;
    }
} 